const config = require('../config')

module.exports = (conf) => {
    if (conf.success) delete conf.success
    if (conf.fail) delete conf.fail
    if (!conf.method) conf.method = 'POST'

    return new Promise((resolve, reject) => {
        const obj = Object.assign({
            timeout: 15000, // 15秒超时
            dataType: 'json',
            header: {
                'Content-Type': 'application/json'
            },
            success (res) {
                if (Number(res.data[config.httpFlag.codeName]) === config.httpFlag.codeSuccess) {
                    resolve(res.data[config.httpFlag.dataName])
                } else if (Number(res.data[config.httpFlag.codeName]) === config.httpFlag.codeFail) {
                    wx.showToast({
                        title: res.data[config.httpFlag.mesName] || '服务开小差啦',
                        icon: 'none'
                    })
                    reject(res.data)
                } else if (Number(res.data[config.httpFlag.codeName]) === config.httpFlag.tokenTimeout) {
                    wx.clearStorageSync()
                    wx.reLaunch({
                        url: '/pages/index/index'
                    })
                    reject(res.data)
                }
            },
            fail (error) {
                console.error('request => fail => error message', error)
                getApp().log.error('request => fail => error message', error)
                let currentPage = getCurrentPages()[0].is
                if (currentPage !== 'pages/networkError/networkError') {
                    wx.navigateTo({
                        url: '/pages/networkError/networkError'
                    })
                }
                reject(error)
            },
            complete: (res) => {
                setCookie(res.header)
            }
        }, conf || {})
        obj.url = config.baseUrl + obj.url
        if (getCookie()) {
            obj.header.Cookie = getCookie()
        }
        if (getToken()) {
            obj.header['X-Token'] = getToken()
        }
        wx.request(obj)
    })
}

function setCookie (header) {
    if ('Set-Cookie' in header || 'set-cookie' in header) {
        wx.setStorageSync(config.cookieName, header['Set-Cookie'] || header['set-cookie'])
    }
}

function getCookie () {
    return wx.getStorageSync(config.cookieName)
}

function getToken () {
    return wx.getStorageSync(config.tokenName)
}